/**
 * Created by weng on 2018/4/5.
 */
/**
 * Created by zhuangy on 2018/3/9.
 */
var sea = require('../common/sea');
var sqlOrm = require('../common/sqlModel');


class Question {
  // http://127.0.0.1:8083/wx/1001/bussInfo/xxxx/code
  async startQuestion(roomInfo,roomNum) {
    try {
      console.log("roomInfo.clients",roomInfo)
      let clients = roomInfo.clients[roomNum]
      let maxNum = roomInfo.questionNum;
      if (!roomInfo.questions[roomNum])
        roomInfo.questions[roomNum] = {};
      let qLength = await sqlOrm.questionLister.countAsync({});
      await sendQuestion(roomInfo,roomNum,clients,qLength,maxNum,maxNum)

    } catch (err) {
      console.error("err",err);
    }
  }

  init(){
    try {
      global.RoomNumType = [2,50,100];
      global.clients = {};
      global.countNum = 0;
      global.questions = {};
      setTimeout(async function () {
        let rooms = await sqlOrm.roomInfo.findAsync({status:1})

        global.roomsAccount = {};
        for(var i of rooms){
          console.log("i.type",i.type)
          let rewardInfo = await sqlOrm.reward.findAsync({type:i.type})
          console.log("rewardInfo",rewardInfo[0])
          let rate = Math.floor(Math.random()* rewardInfo[0].rate)
          global.roomsAccount[i.type] = {rate:[rate],roomNum:0,clients:[],questions:{},questionNum :i.questionNum}
        }
      },1000)

    }catch (e){
      console.error("err ",e)
    }

  }
}
var finishAnswer = async function (clients,roomInfo,roomNum) {
  try {
    // clients.sort(compare('score'))
    console.log("发放奖励")
    /// 依据排名发放奖励
    for(var i in clients){
      console.log("iiiii",i)
      let rewardInfo = await sqlOrm.reward.findAsync({type:clients[i].roomType})
      if(clients[i].answerStaus)continue


      let rate = roomInfo['rate'][roomNum] //Math.floor(Math.random()* rewardInfo[0].rate)
      num =  clients.length + rate

      console.log("parseInt(rewardInfo[0].golden)/num",parseInt(rewardInfo[0].golden)/num)

      clients[i].accountInfo.golden += parseInt(rewardInfo[0].golden)/num
      clients[i].accountInfo.saveAsync()
      clients[i].emit("endQuestion",{golden: parseInt(rewardInfo[0].golden)/num})

      /// 断开链接
      clients[i].disconnect()
    }
  }catch (e){
    console.error("eeeeee",e)
    global.loggersFile.error("finishAnswer false :", e);
  }
}


function compare(property){
  return function(a,b){
    var value1 = a[property];
    var value2 = b[property];
    return value1 - value2;
  }
}
var sendQuestion = async function (roomInfo,roomNum,clients,qLength,maxNum,curNum) {
  // 没隔 15秒推送一条题目
  try {
    let rate = roomInfo['rate'][roomNum] //Math.floor(Math.random()* rewardInfo[0].rate)
    let rightNum = 0
    for(let i in clients){
      console.log("clients",clients[i].answered)
      console.log("answerWrong",clients[i].answerWrong)
      if(clients[i].answered){
        if(!clients[i].answerWrong){
          rightNum ++
        }
      }
    }

    console.log("rate",rate)
    console.error("clients.length + rate",rightNum + rate)
    console.error("clients.length + rate",rightNum + rate == 1)

    if (curNum <= 0 || (curNum!= maxNum && rightNum + rate == 1)) {

      //结束答题结算排名断开链接
      setTimeout(async function () {
        await finishAnswer(clients,roomInfo,roomNum)
        roomInfo.questions[roomNum] = []
      },1000 * 5)
      console.error("这里return",curNum)
      return
    };

    console.error("这里继续",curNum)

    let nextTiime = 5;
    if(maxNum == curNum){
      nextTiime = 3
    }
    setTimeout(async function () {
      let question = await  getQuestion(qLength)
      roomInfo.questions[roomNum] = {...question,time:new Date().getTime()}
      console.log("clients",clients.length)
      console.error("curNum",curNum)

      for(var client of clients){
        if(clients.answerStaus == -1){
          console.log("题目 答题错误断开 answerStaus",client.accountid)
          client.disconnect()
          //return
        }

        if(client.answered == 0){
          console.log("题目 没有答题断开 ",client.accountid)
          client.disconnect()
          continue
        }

        if(client.answerWrong){
          console.log("题目 答题错误 ",client.accountid)
          client.disconnect()
          continue
        }

        console.log("题目",client.accountid)
        client.answered = 0
        client.emit("questionInfo",{ questionId:question.id,question:question.question,answerList:question.answerList,maxNum:maxNum,curNum:(maxNum -curNum) + 1})
      }
      /// 10秒后通知答案
      setTimeout(async function () {
        //for(var client of clients){
        //  //if(clients.answerStaus == -1)continue
        //	console.log("答案",client.accountid)
        //    client.emit("answerInfo",{ questionId:question.id,question:question.question,answerList:question.answerList,
        //    answer:question.answer,time:new Date().getTime(),score:client.score,count:clients.length})
        //
        //	if(client.answerWrong){
        //		console.log("答案 答题错误断开 ",client.accountid)
        //		client.disconnect()
        //		//continue
        //	}
        //	 if(client.answered == 0){
        //		console.log("答案 没有答题断开 ",client.accountid)
        //		client.disconnect()
        //		//continue
        //	}
        //
        //
        //}
        if(clients.length <= 0) return;




        num =  rightNum + rate
        for(let i in clients){
          //if(clients.answerStaus == -1)continue
          console.log("答案",clients[i].accountid)
          console.log("rightNum",num)


          clients[i].emit("answerInfo",{ questionId:question.id,question:question.question,answerList:question.answerList,
            answer:question.answer,time:new Date().getTime(),score:clients[i].score,count:num})

          if(clients[i].answerWrong){
            console.log("答案 答题错误断开 ",clients[i].accountid)
            clients[i].disconnect()
            continue
          }
          if(clients[i].answered == 0){
            console.log("答案 没有答题断开 ",clients[i].accountid)
            clients[i].disconnect()
            continue
          }

        }

        await sendQuestion(roomInfo,roomNum,clients,qLength, maxNum,curNum-1)
      },10 * 1000)


    },nextTiime * 1000 )
  }catch (e){
    console.error("err",e)
  }
}
var getQuestion = async function (qLength) {
  console.log("qLength",qLength)
  let id = Math.floor(Math.random()* qLength) ;
  console.log("id",id)
  let question = (await sqlOrm.questionLister.findAsync({id}));
  if(question.length <= 0){
    return question = await getQuestion(qLength)
  }
  return question[0]
}

module.exports = new Question();